package com.su.gulimall.product.exception;


import com.su.common.exception.BizCodeEnume;
import com.su.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

//集中处理所有异常
//该注解实现哪个包下的异常会匹配到该处理类
@Slf4j
@RestControllerAdvice(basePackages = "com.su.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    //对哪个异常类型进行处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e)
    {
        HashMap<String, Object> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(
                (item)->{
                    String message=item.getDefaultMessage();
                    String filed=item.getField();
                    map.put(filed,message);
                });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }
    //对其他异常进行管理
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable)
    {

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg());
    }



}
